import { Route, Switch, Redirect } from "react-router-dom";
import routesConfig from "./config";
import AllComponents from "@/pages/index";

// 找出需要渲染的数据
const candleRoute = () => {
  // let menus = JSON.parse(localStorage.getItem("menus") || "");
  let menus = routesConfig.sideMenus;
  let result: any = [...routesConfig.others];
  menus.map((item: any) => {
    if (item.sub && !item.sub.length) {
      result.push(item);
    } else {
      item.sub.map((subItem: any) => {
        result.push(subItem);
      });
    }
  });
  return result;
};

const CRouter = () => {
  let routes: any = candleRoute();

  const createMenu = (r: any) => {
    const Component = AllComponents[r.component];

    return (
      <Route
        exact
        key={r.path}
        path={r.path}
        render={(props: any) => {
          return (
            <div className="content">
              {Component ? <Component {...props} /> : <div>{r.menu_name}</div>}
            </div>
          );
        }}
      />
    );
  };

  return (
    <Switch>
      {routes.map((item: any) => createMenu(item))}
      <Route render={() => <Redirect to="/dashboard" />} />
    </Switch>
  );
};

export default CRouter;
